<?php

declare (strict_types = 1);

namespace own\tripartite;

use own\enum\FileEnum;
use own\helps\OwnFunc;
use think\facade\Cache;
use think\facade\Config;

/**
 * 微信小程序
 */
class WeChatApplet
{
    /**
     * 获取AccessToken
     */
    public function getAccessToken(): string
    {
        $wx = Config::get('pay.wechat.default');
        //获取缓存 access_token
        $accessToken = Cache::get('wx_access_token');
        if (!$accessToken) {
            $param = [
                'grant_type' => 'client_credential',
                'appid' => $wx['mini_app_id'],
                'secret' => $wx['mini_secret'],
            ];
            $response = OwnFunc::curlPost('https://api.weixin.qq.com/cgi-bin/token', $param);
            if (isset($response['errcode']) && $response['errcode'] != 0) {
                tips('获取微信签名失败');
            }
            //放入缓存
            $accessToken = $response['access_token'];
            Cache::set('wx_access_token', $accessToken, 6000);
        }
        return $accessToken;
    }
    /**
     * 获取微信授权手机号
     * @param $code
     */
    public function getUserPhone($code): array
    {
        $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $this->getAccessToken();
        $response = OwnFunc::curlPost($url, ['code' => $code], [
            "Content-type:text/plain;charset='utf-8'", 
            "Accept:application/json"
        ]);
        if (isset($response['errcode']) && $response['errcode'] != 0) {
            tips('获取手机号失败');
        }
        return $response;
    }
    /**
     * 获取微信用户openid
     * @param string $code
     */
    public function getWxOpenId(string $code): string
    {
        $wx = Config::get('pay.wechat.default');
        $param = [
            'appid' => $wx['mini_app_id'],
            'secret' => $wx['mini_secret'],
            'js_code' => $code,
            'grant_type' => 'authorization_code',
        ];
        $response = OwnFunc::curlGet('https://api.weixin.qq.com/sns/jscode2session', $param);
        if (isset($response['errcode']) && $response['errcode'] != 0) {
            tips('请重新授权登录');
        }
        $openid = $response['openid']??'';
        if(!$openid) {
            tips('请重新授权登录');
        }
        return $openid;
    }
    /**
     * 生成微信小程序邀请二维码
     * @param string $pid 会员id
     */
    public function getWxQrcode($pid): string
    {
        $response = OwnFunc::curlPost('https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $this->getAccessToken(), 
            ['page' => 'pages/index/index', 'width' => 200, 'scene' => 'pid=' . $pid, 'is_hyaline' => true], 
            [], false);
        if (isset($response['errcode'])) {
            tips('获取邀请二维码失败，' . $response['errmsg']);
        }
        //将数据流写入文件
        list($path, $url) = make(FileEnum::class)->storageName('.png', FileEnum::QRCODE);
        file_put_contents($path, $response);
        return $url;
    }
    
}
